/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.util.request;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import yhao.infra.apilist.RequestResult;

import java.util.Map;

import static org.springframework.http.HttpMethod.*;

/**
 * 这个包存在的意义只是演示另一种请求的方式
 *
 * @author yoara
 */
public class ApiRequestUtil {
    /**
     * ribbon方式远程请求方法
     * @param request
     * @return
     */
    protected static <T> RequestResult<T> requestApi(RestTemplate restTemplate,ApiServiceRequest request) {
        if (request == null) {
            throw new InitRequestException("请配置请求参数");
        }
        String uri = request.getUri() + request.parameterMapToUriTailString();
        if (request.getMethod().equals(GET)) {
            if (request.getUrlVariables() == null || request.getUrlVariables().size() == 0) {
                ParameterizedTypeReference<RequestResult<T>> typeRef = new ParameterizedTypeReference<>() {
                };
                ResponseEntity<RequestResult<T>> responseEntity = restTemplate.exchange(uri, GET, null, typeRef);
                return responseEntity.getBody();
            }
            return restTemplate.getForEntity(uri, RequestResult.class, request.getUrlVariables()).getBody();
        } else if (request.getMethod().equals(POST)) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<Map> formEntity =
                    new HttpEntity<>(request.getParameterMap(), headers);
            if (request.getUrlVariables() == null || request.getUrlVariables().size() == 0) {
                return restTemplate.postForEntity(uri, formEntity, RequestResult.class).getBody();
            } else {
                return restTemplate.postForEntity(
                        uri, formEntity, RequestResult.class, request.getUrlVariables()).getBody();
            }
        }
        throw new InitRequestException("错误的请求类型");
    }
}
